package model

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"logprocess/pkg/setting"
	"time"
)

type AccessLog struct {
	ID        int
	TimeLocal time.Time
	BytesSent int
	Ip        string `gorm:"size:20"`
	Path      string
	Method    string `gorm:"size:10"`
	Status    string `gorm:"size:10"`
	UserAgent string
}

type AccessLogSummary struct {
	ID          int    // ID
	SummaryDate string `gorm:"size:10"` // 日期
	Pv          int    `gorm:"size:11"` // page view
	Uv          int    `gorm:"size:11"` // user view
}

func (AccessLog) TableName() string {
	// 当天日期
	date := time.Now().Format("20060102")
	// 表名
	tableName := "access_log"
	// tbl_access_log_20210831
	return fmt.Sprintf("%s%s_%s", setting.DbSetting.TablePrefix, tableName, date)
}

// 创建前调用
func (accessLog *AccessLog) BeforeCreate(tx *gorm.DB) (err error) {
	fmt.Println("==BeforeCreate==")
	if !db.AutoMigrate().HasTable(&AccessLog{}) {
		db.AutoMigrate(&AccessLog{})
	}
	return
}

// 创建日志
func (accessLog *AccessLog) Create() bool {
	err := db.Create(accessLog).Error
	if err != nil {
		return false
	}
	// 更新统计
	accessLog.updateSummary()
	return true
}

func (accessLog *AccessLog) updateSummary() bool {
	date := time.Now().Format("2006-01-02")

	summary := AccessLogSummary{SummaryDate: date}
	err := db.First(&summary).Error
	if err != nil { // 创建
		summary.Pv = 1
		summary.Uv = 1
		db.Create(&summary)
	} else { // 更新
		var count int
		summary.Pv = summary.Pv + 1
		db.Model(&AccessLog{}).Where("ip=?", accessLog.Ip).Count(&count)
		if count == 1 {
			summary.Uv = summary.Uv + 1
		}
		db.Model(&AccessLogSummary{}).Update(&summary)
	}
	return true
}

func Ping() {
	accessLog := &AccessLog{
		0,
		time.Now(),
		100,
		"192.168.1.2",
		"/",
		"GET",
		"200",
		"",
	}
	accessLog.Create()
}
